#endcoding:utf-8
class DemandsController < ApplicationController
  before_action :store_location
  before_action :logged_in?,only:[:new,:create,:destroy]
  before_action :counselorgo ,only:[:new]
  layout "user"
  def index
    @kw = params[:kw].nil? ? '' : params[:kw]
    if params[:stat].nil?
      @demands = Demand.includes(:offers).where("projects like '%#{@kw}%'").order('created_at desc').paginate :page=> params[:page],:per_page=> 12
    else
      @demands = Demand.includes(:offers).where("projects like '%#{@kw}%' AND status=#{params[:stat].to_s}").order('created_at desc').paginate :page=> params[:page],:per_page=> 12
    end
  end
  def new

    if session[:user_id].nil?
      redirect_to login_path
    end
    store_location
    if !getcardinfo(userinfo)
      flash[:danger]="请先完善个人信息，才能发布需求"
      redirect_to '/editinfo'
    end
    @demand = Demand.new
  end


  def create
    @demand = Demand.new(demand_params)
    if @demand.save
      flash[:danger] = "发布成功，等待咨询师来投标吧"
      redirect_to @demand
    else
      flash[:danger] = @demand.errors.full_messages[0]
      render "new"
    end
  end
  def show
    @demand = Demand.find(params[:id])
    read(@demand)
    @title = @demand.projects
    if @demand.status>1
      @deal = Deal.where("demand_id="+@demand.id.to_s)
      @offers = Offer.where("id="+@deal[0].offer_id.to_s).paginate :page=> params[:page],:per_page=> 12
    else
      @offers = @demand.offers.paginate :page=> params[:page],:per_page=> 12
    end
  end
  def update
    ActiveRecord::Base.transaction do
      @demand = Demand.find(params[:id])
      if @demand.update(:status=>params[:demand][:status])
        @deal = Deal.find_by(:demand_id=>@demand.id)
        @offer = Offer.find(@deal.offer_id)
        @offer_user_id = @offer.user_id
        content = message_link "您的订单厂家已经确定完成！",demand_path(@demand)
        send_message @offer_user_id,content,params[:id]
        render :json=>{:stat=>1}
      end
    end
  end
  private
  def demand_params
    @tag = Tag.store_tag(params[:demand])
    params[:demand][:tag_id] = @tag.id
    params[:demand].store("status",1)
    params.require(:demand).permit(:projects,:description,:user_id,:status,:tag_id)
  end
  def read(demand)
    remoteip = request.remote_ip
    demand_read_log = DemandReadLog.where('remote_ip="'+remoteip+'" AND demand_id='+demand.id.to_s)
    if !demand_read_log.any?
      demand.update_attribute(:read_num,demand.read_num+1)
      DemandReadLog.new({:remote_ip=>remoteip,:demand_id=>demand.id}).save
    end
  end
end
